package com.wjf.birdfish.hibernate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public abstract class AbstractPage<T> implements Page<T>{
    protected int pageIndex;
    protected int pageNumber = 1;
    protected int pageSize;
    protected int recordNumber;
    protected List<T> data;
    
    public int getPageIndex() {
        return pageIndex;
    }

    public Page<T> nextPage() {
        if (pageIndex < pageNumber) {
            ++pageIndex;
        }
        gotoPage(pageIndex);
        return this;
    }

    public Page<T> prevPage() {
        if (pageIndex > basePageIndex()) {
            --pageIndex;
        }
        gotoPage(pageIndex);
        return this;
    }

    public Page<T> lastPage() {
        if (pageNumber > basePageIndex()) {
            pageIndex = pageNumber - 1;
        }
        gotoPage(pageIndex);
        return this;
    }

    public Page<T> firstPage() {
        gotoPage(basePageIndex());
        return this;
    }

    public int getPageSize() {
        return pageSize;
    }

    public int getPageNumber() {
        return pageNumber;
    }

    protected int basePageIndex() {
        return 0;
    }

    public int getRecordNumber() {
        return recordNumber;
    }

    protected int computeMaxResults() {
        if (pageSize <= 0) {
            pageSize = Integer.MAX_VALUE;
        }
        return pageSize;
    }

    protected int computeFirstResult() {
        return pageIndex * pageSize;
    }

    public void saveTo(HttpServletRequest request) {
        saveTo(request, REQUEST_SCOPE);
    }

    public void saveTo(HttpServletRequest request, int scope) {
        switch (scope) {
            case REQUEST_SCOPE:
                request.setAttribute(PAGE_KEY, this);
                break;
            case SESSION_SCOPE:
                request.getSession().setAttribute(PAGE_KEY, this);
                break;
        }
    }

    public Page<T> gotoPage(int pageIndex) {
        if (pageIndex < basePageIndex()) {
            firstPage();
        } else if (pageIndex > pageNumber) {
            lastPage();
        } else {
            this.pageIndex = pageIndex;
        }
        refresh();
        return this;
    }

    protected void refresh() {
        data = null;
        getData();   
    }
    
    protected void setPageNumber() {
		if (getPageSize() > 0) {
			pageNumber = recordNumber / getPageSize();
			if (recordNumber % getPageSize() != 0) {
				++ pageNumber;
			}
		}
	}

}
